<template>
  <div class="login">
    <Particles id="tsparticles" class="login__particles" :options="options" />

    <div class="loginPart">
      <h2>用户注册</h2>
      <el-form 
        aria-autocomplete="off" 
        :model="registerForm" 
        ref="registerFormRef" 
        :rules="rules" 
        label-width="100px"
        style="transform: translate(-30px)"
      >
        <el-form-item label="账号" prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="registerForm.password" placeholder="请输入密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input type="password" v-model="registerForm.confirmPassword" placeholder="请确认密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone_number">
          <el-input v-model="registerForm.phone_number" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email" placeholder="请输入邮箱（选填）"></el-input>
        </el-form-item>

        <el-button class="btn" type="primary" @click="register">注册</el-button>
        <div style="text-align: right; transform: translate(0, 30px)">
          <el-link type="success" @click="goToLogin">已有账号？去登录</el-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import axios from "@/utils/http"; // 确保已正确配置 Axios 工具文件
import qs from 'qs'; // 安装 qs 库以处理 URL 编码
import '../components/UserRegister.scss'

// 路由实例
const router = useRouter();

// 表单数据
const registerForm = reactive({
  username: "",
  password: "",
  confirmPassword: "",
  phone_number: "",
  email: ""

});

// 表单引用
const registerFormRef = ref(null);

// 表单验证规则
const rules = {
  username: [
    { required: true, message: "请输入账号", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        // 自定义验证逻辑：账号必须是2-6位的中文、数字或字母组合
        const accountPattern = /^[\u4e00-\u9fa5a-zA-Z0-9]{2,6}$/;
        if (!value || accountPattern.test(value)) {
          callback(); // 验证通过
        } else {
          callback(new Error("账号格式不正确（2-6位的中文、数字或字母组合）"));
        }
      },
      trigger: ["blur", "change"],
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度应在6到20个字符之间", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请再次输入密码"));
        } else if (value !== registerForm.password) {
          callback(new Error("两次密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  email: [
    // 非必填，但如果有值则需要符合邮箱格式
    { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }
  ],
  phone_number: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    // 非必填，但如果有值则需要符合手机号格式
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: ["blur", "change"] }
  ]
};

// 注册逻辑
const register = async () => {
  try {
    // 表单验证
    await registerFormRef.value.validate();
    // 发送请求
    axios.post("/register/", qs.stringify(registerForm), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
      .then((res) => {
        if (res.data.code === 200) {
          ElMessage.success("注册成功");
          router.push("/login");
        } else {
          ElMessage.error(res.data.message || "注册失败，请检查账号或密码");
        }
      })
      .catch((error) => {
        if (error.response) {
          // 后端返回的错误信息
          if (error.response.status === 404) {
            ElMessage.error("请求的接口不存在，请检查后端配置");
          } else {
            ElMessage.error(error.response.data.message || "服务器内部错误");
          }
        } else {
          // 其他网络错误
          ElMessage.error("网络请求失败，请稍后再试");
        }
        console.error("注册失败:", error);
      });
  } catch (error) {
    console.error("表单验证失败:", error);
  }
};

// 跳转到登录页面
const goToLogin = () => {
  router.push("/login");
};

// 粒子效果配置
const options = {
  fpsLimit: 60,
  interactivity: {
    detectsOn: "canvas",
    events: {
      onClick: {
        enable: true,
        mode: "push",
      },
      onHover: {
        enable: true,
        mode: "grab",
      },
      resize: true,
    },
    modes: {
      bubble: {
        distance: 400,
        duration: 2,
        opacity: 0.8,
        size: 40,
      },
      push: {
        quantity: 4,
      },
      grab: {
        distance: 200,
        duration: 0.4,
      },
      attract: {
        distance: 200,
        duration: 0.4,
        factor: 5,
      },
    },
  },
  particles: {
    color: {
      value: "#BA55D3", // 粒子点的颜色
    },
    links: {
      color: "#FFBBFF", // 线条颜色
      distance: 150, // 线条距离
      enable: true,
      opacity: 0.4, // 不透明度
      width: 1.2, // 线条宽度
    },
    collisions: {
      enable: true,
    },
    move: {
      attract: { enable: false, rotateX: 600, rotateY: 1200 },
      bounce: false,
      direction: "none",
      enable: true,
      out_mode: "out",
      random: false,
      speed: 0.5, // 移动速度
      straight: false,
    },
    number: {
      density: {
        enable: true,
        value_area: 800,
      },
      value: 80, // 粒子数
    },
    opacity: {
      value: 0.7,
    },
    shape: {
      type: "star",
    },
    size: {
      random: true,
      value: 3,
    },
  },
  detectRetina: true,
};
</script>

